package item

import (
	"github.com/gogf/gf/v2/os/gmlock"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/event"
	"xr-game-server/gamecfg"
	"xr-game-server/gameevent"
	"xr-game-server/module/protocol"
)

// Consume 批量消费物品 消费金币,道具
func Consume(roleId uint64, items [][]uint64, canPush bool) bool {
	itemLock := getLockStr(roleId)
	gmlock.Lock(itemLock)
	defer gmlock.Unlock(itemLock)
	if len(items) == common.Zero {
		return false
	}
	itemModels := protocol.NewItemModels(items)
	typeMap := make(map[uint32][]*protocol.ItemModel)
	//检查是否满足数量
	for _, item := range itemModels {
		itemCfg := gamecfg.GetItemById(item.Id)
		if itemCfg == nil {
			return false
		}
		handler := protocol.GetItemHandlerBy(itemCfg.ItemHandler)
		if handler == nil {
			return false
		}
		if !handler.CanConsume(roleId, item) {
			return false
		}
		typeModels, ok := typeMap[itemCfg.ItemHandler]
		if !ok {
			typeModels = make([]*protocol.ItemModel, common.Zero)
			typeMap[itemCfg.ItemHandler] = typeModels
		}
		typeModels = append(typeModels, item)
		typeMap[itemCfg.ItemHandler] = typeModels
	}
	//分类批量消费
	for key, val := range typeMap {
		handler := protocol.GetItemHandlerBy(key)
		handler.Consume(roleId, val, canPush)
	}
	//发送物品日志
	event.Pub(gameevent.ItemChange, gameevent.NewItemChangeData(roleId, itemModels))
	return true
}
